<?php
namespace app\api\controller\vppz;

use think\Cache;
use EasyWeChat\Factory as EasyWeChatFactory;


class Auth extends AppBase
{
    //protected $noNeedLogin = ['*'];
    //protected $noNeedRight = ['*'];


    /**
     * 微信小程序登录接口code换openid..，对应前端wx.login()
     */
    public function wxLogin(){
        //$miniProgram = Facade::miniProgram(); // 小程序
		$_cfg = $this->_cfg;
		// 初始化小程序接口SDK
		$WxappApi = EasyWeChatFactory::miniProgram([
			'app_id'    => $_cfg['wxapp_id'],
			'secret'    => $_cfg['wxapp_secret'],
			//'token'     => 'easywechat',
			'log' => [
				'level' => 'debug',
				'file'  => '/tmp/easywechat.log',
			],
			// ...
		]);

		// 小程序端得到用户码，发给微信换取openid
		$code = input("code");
		$vipcode = input("vipcode",'');
		if(empty($code)){
			$this->error('缺少参数');
		}
		$oauth = $WxappApi->auth->session($code);
		if(empty($oauth['openid'])){
			$this->error('微信授权登录失败。errcode:'.$oauth['errcode'].'errmsg:'.$oauth['errmsg']);
		}
		// 根据 oauth['openid'] 在应用中获取用户信息，如果没有则自动创建
		$user = $this->UserModel->where(array('openid'=>$oauth['openid']))->find();
		if(empty($user)){
			$user=array(
				'app_id'=>$this->app_id,
				'openid'=>$oauth['openid']
			);
            $card = [];
            if(empty($vipcode) === FALSE){
                $card = $this->VipCardModel->where([
                    'code'=>$vipcode,
                    'status'=>0
                ])->find();
                if(empty($card) === FALSE){
                    $user['is_vip'] = 1;
                    $user['vip_time'] = datetime(time(),'Y-m-d H:i:s');
                    $user['expire_time'] = datetime(strtotime("+".$card['duration']." months", time()),'Y-m-d H:i:s');
                }
            }
			$this->UserModel->save($user);
			$user_id = $this->UserModel->id;
            if(empty($card) === FALSE){
                $this->VipCardModel->where([
                    'id'=>$card['id']
                ])->update(array(
                    'status'=>1,
                    'user_id'=>$user_id,
                    'updatetime'=>time()
                ));
            }
			if(!($user_id>0)){
				$this->error('用户自动登录失败，请重试');
			}
			$user = $this->UserModel->find($user_id);
		}else{
            if(empty($vipcode) === FALSE){
                $card = $this->VipCardModel->where([
                    'code'=>$vipcode,
                    'status'=>0
                ])->find();
                if(empty($card) === FALSE){
                    if($user['is_vip'] == 0) {
                        $updatedata = [];
                        $updatedata['is_vip'] = 1;
                        $updatedata['vip_time'] = datetime(time(), 'Y-m-d H:i:s');
                        $updatedata['expire_time'] = datetime(strtotime("+" . $card['duration'] . " months", time()), 'Y-m-d H:i:s');
                    }else{
                        $updatedata['expire_time'] = datetime(strtotime("+" . $card['duration'] . " months", strtotime($user['expire_time'])), 'Y-m-d H:i:s');
                    }
                    $updatedata['updatetime'] = time();
                    $this->UserModel->where([
                        'id' => $user['id']
                    ])->update($updatedata);
                    $this->VipCardModel->where([
                            'id'=>$card['id']
                        ])->update(array(
                            'status'=>1,
                            'user_id'=>$user['id'],
                            'updatetime'=>time()
                        ));
                }
            }
        }

		/***
		$UserModel = new User([
			'openid'  => $oauth['openid'],
		]);
		$UserModel->save();
		**/

		// 生成会话
		// 利用PHP自带函数生成会话ID（可能不安全，暂时使用）
		session_start();
		$sessionid = 'vppzsid-'.session_id();// 加上应用前缀，避免和其他应用重复
		// 存储session
		Cache::set($sessionid,$user['id'],3600);// 会话中只存用户id节省空间,因为小程序前端已经缓存了用户信息
		//session($sessionid,$user['id']);
        $this->success('登录成功',array(
			'sessionid'=>$sessionid,
			'userinfo'=>$user,
			'openid'=>$user['openid']

		));
    }

	public function sessionCheck(){
		$sessionid=input('ssid');

		if(empty($sessionid)){
			$this->error('会话无效，请重新发起登录请求');
		}
		$user_id = Cache::get($sessionid);
		//$user_id = session($sessionid);
		if(empty($user_id)){
			$this->error('会话失效，请重新发起登录请求');
		}else{
            Cache::set($sessionid,$user_id,3600);
			 $this->success();
		}
	}
	//session


}
